<?php


namespace app\controller\admin;


use app\BaseController;
use think\facade\Db;

class PaintController extends BaseController
{
    public function getList()
    {
        try {
            $where = [];
            $params = $this->request->param();
            if (isset($params['user_name'])) {
                $where[] = ['b.user_name', 'like', '%' . trim($params['user_name']) . '%'];
            }
            if (isset($params['mobile'])) {
                $where[] = ['b.mobile', 'like', '%' . trim($params['mobile']) . '%'];
            }
            $list = Db::name('paint')
                ->alias('a')
                ->leftJoin('user b', 'b.id = a.customer_id')
                ->field('a.*,b.user_name,b.mobile')
                ->where($where)
                ->order('a.id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function add()
    {
        try {
            $mobile = $this->request->param('mobile');
            $prefix = $this->request->param('paint_prefix');
            $code = $this->request->param('paint_code');
            $name = $this->request->param('paint_name');
            $userInfo = Db::name('user')->where('mobile', $mobile)->find();
            if (!$userInfo) {
                throw new \Exception('手机号错误');
            }
            $id  = $this->request->param('id');
            if(!$id){
                $list = Db::name('paint')->insert([
                    'customer_id' => $userInfo['id'],
                    'paint_name' => $name,
                    'paint_prefix' => $prefix,
                    'paint_code' => $prefix . $code,
                    'relation' => $userInfo['relation'],
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }else{
                $list = Db::name('paint')->where('id',$id)->update([
                    'paint_name' => $name,
                    'paint_prefix' => $prefix,
                    'paint_code' => $prefix . $code,
                ]);
            }

            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function upgrade()
    {
        try {
            $id = $this->request->param('id');

            $info = Db::name('paint')->where('id', $id)->find();
            if (!$info) {
                throw new \Exception('非法请求');
            }
            if ($info['level'] == 1) {
                throw new \Exception('已经是母宝阁');
            }
            Db::name('paint')->where('id', $id)->update(['level' => 1]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}